﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Lon.Collect
{
    public class CycleArray<T>
    {
        private T[] buf;
      
        private int capacity;

        private int count;

        public int Count
        {
            get { return count; }
        }
        
       

        public CycleArray(int length)
        {
           this.capacity=CalcCapacity(length);
           this.buf = new T[capacity];
        }

        public T  this[int index]
        {
            get
            {
                lock(this)
                {
                    if (index >= this.count)
                    {
                        throw new Exception("超出数组边界");
                    }
                    int realIndex = this.position-this.count + index+1;
                    realIndex &= (this.capacity - 1);
                    return this.buf[realIndex];
                }

            }



        }

        public T[] ToArray()
        {
            lock(this)
            {
                T[] ret = new T[this.Count];
                for(int i=0;i<this.count;i++)
                {
                    ret[i] = this[i];
                }
                return ret;
            }
        }
        int position = 0;
        
        /// <summary>
        /// 容量使用2的N次方
        /// 最小为0x10
        /// 最多为0x1000
        /// </summary>
        /// <param name="length"></param>
        private int CalcCapacity(int length)
        {
           for(int i=0;i<8;i++)
           {
              if(length<(0x10<<i))
              {
                  return 0x10 << i;
              }
           }
           return 0x1000;
        }
        public void  Add(T val)
        {
            lock(this)
            {
              position++;
              position&=(this.capacity-1);
              this.buf[position] = val;
              if(this.count<this.capacity)
              {
                  this.count++;
              }
            }
        }
    }
}
